﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Threading.Tasks;
using DocumentFormat.OpenXml.Wordprocessing;
using Newtonsoft.Json;
using NP.BPMReportPlatform.BPMPlatform;
using NP.BPMReportPlatform.CommonEnum;
using NP.BPMReportPlatform.DBHelper;
using NP.BPMReportPlatform.Entities.BPM_Business;
using NP.BPMReportPlatform.Entities.BPM_Business.DesignDependencyBook;
using NP.BPMReportPlatform.Entities.BPM_Engine;
using NP.BPMReportPlatform.Entities.BPM_Platform;
using NP.BPMReportPlatform.GC.Dto;
using NP.BPMReportPlatform.Utilities;
using NP.BPMReportPlatform.Utils;
using NPOI.SS.Formula.Functions;
using NPOI.SS.Formula.PTG;
using SqlSugar;
using Volo.Abp.Application.Dtos;
using Volo.Abp.Users;

namespace NP.BPMReportPlatform.GC
{
    /// <summary>
    /// 工程接口服务
    /// </summary>
    public class GCAppService : BPMReportPlatformAppService, IGCAppService
    {
        #region Variables

        private readonly SqlSugarClient _db;
        private readonly SqlSugarClient _dbPlatform;
        private readonly IBPMUtilsAppService _bPMUtilsApp;
        private readonly IBPMPlatformAppService _iBPMPlatformApp;
        private readonly SqlSugarClient _dbEngine;

        #endregion

        #region Constructor

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="sqlSugarAppService"></param>
        public GCAppService(ISqlSugarAppService sqlSugarAppService, IBPMUtilsAppService bPMUtilsApp
            , IBPMPlatformAppService iBPMPlatformApp)
        {
            _db = sqlSugarAppService.GetBusinessInstance();
            _dbPlatform = sqlSugarAppService.GetPlatformInstance();
            _dbEngine = sqlSugarAppService.GetEngineInstance();
            _bPMUtilsApp = bPMUtilsApp;
            _iBPMPlatformApp = iBPMPlatformApp;
        }

        #endregion
        #region 小于最低起运量运输申请 报表
        /// <summary>
        /// 获取Queryable
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        private ISugarQueryable<GetXYZDQYLSQOutput> GetQueryableExport(GetXYZDQYLSQInput input)
        {
            var currentUserId = Guid.Empty;
            if (!input.IsQueryAll)
            {
                var currentUserDto = _dbPlatform.Queryable<Users>()
                    .Where(x => x.WorkNumber.Equals(CurrentUser.UserName)).First();
                if (currentUserDto != null)
                {
                    currentUserId = currentUserDto.UserId;
                }
            }
            var listQueryable = _db.Queryable<JJYSSPNewHeader, JJYSSPNewDetail, BusinessProcessesNew>(
                    (x, d, b) => new JoinQueryInfos(JoinType.Left, x.InstanceNumber == d.InstanceNumber, JoinType.Left, x.InstanceNumber == b.InstanceId))
                .Where(x => x.FormType == "XYZDQYLSQ")
                .WhereIF(!string.IsNullOrWhiteSpace(input.InstanceNumber), x => x.InstanceNumber == input.InstanceNumber)
                .WhereIF(!input.IsQueryAll, x => x.AddUserId.Equals(currentUserId))
                .WhereIF(!input.OrderStatus.IsNullOrEmpty(), (x, d, b) => SqlFunc.ContainsArray(input.OrderStatus.ToArray(), b.ProcessStatusCode))
                .WhereIF(!string.IsNullOrWhiteSpace(input.AddUserName), x => x.AddUserName.Contains(input.AddUserName))
                .WhereIF(input.StartCreationTime != null && input.EndCreationTime != null,
                    x => x.AddTime >= input.StartCreationTime && x.AddTime <= input.EndCreationTime)
                .Select((x, d, b) =>
                    new GetXYZDQYLSQOutput()
                    {
                        InstanceNumber = x.InstanceNumber,
                        CreateTime = x.AddTime,
                        CreateTimeStr = x.AddTime != null ? x.AddTime.ToString(DateFormatHelper.DateTimeFormat) : "",
                        AddUserName = x.AddUserName,
                        OrderStatus = b.ProcessStatusName,
                        JfyyzyName = x.JfyyzyName,
                        RequestArrivalDate = x.RequestArrivalDate,
                        BusinessNo = x.BusinessNo,
                        BusinessName = x.BusinessName,
                        CustomerCode = x.CustomerCode,
                        CustomerName = x.CustomerName,
                        BigCustomerCode = x.BigCustomerCode,
                        BigCustomerName = x.BigCustomerName,
                        XSBName = x.XSBName,
                        XSYName = x.XSYName,
                        CostCentre = x.CostCentre,
                        CostCentreName = x.CostCentreName,
                        TotalCost = x.TotalCost,
                        TotalWeight = x.TotalWeight,
                        ApplicationReason = x.ApplicationReason,
                        No = d.No,
                        DeliveryNoteNo = d.DeliveryNoteNo,
                        DeliveryAddress = d.DeliveryAddress,
                        Factory = d.Factory,
                        OutboundWeight = d.OutboundWeight,
                        ExpeditedShippingAmount = d.ExpeditedShippingAmount,
                        InvoiceAmount = d.InvoiceAmount,
                        TransportRatio = d.TransportRatio

                    }).MergeTable().Distinct().OrderBy(ins => ins.CreateTime, OrderByType.Desc);

            return listQueryable;
        }
        /// <summary>
        /// 获取Queryable
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        private ISugarQueryable<GetXYZDQYLSQOutput> GetQueryable(GetXYZDQYLSQInput input)
        {
            var currentUserId = Guid.Empty;
            if (!input.IsQueryAll)
            {
                var currentUserDto = _dbPlatform.Queryable<Users>()
                    .Where(x => x.WorkNumber.Equals(CurrentUser.UserName)).First();
                if (currentUserDto != null)
                {
                    currentUserId = currentUserDto.UserId;
                }
            }
            var listQueryable = _db.Queryable<JJYSSPNewHeader, BusinessProcessesNew>(
                    (x,  b) => new JoinQueryInfos(JoinType.Left, x.InstanceNumber == b.InstanceId))
                .Where(x => x.FormType == "XYZDQYLSQ")
                .WhereIF(!string.IsNullOrWhiteSpace(input.InstanceNumber), x => x.InstanceNumber == input.InstanceNumber)
                .WhereIF(!input.IsQueryAll, x => x.AddUserId.Equals(currentUserId))
                .WhereIF(!input.OrderStatus.IsNullOrEmpty(), (x, b) => SqlFunc.ContainsArray(input.OrderStatus.ToArray(), b.ProcessStatusCode))
                .WhereIF(!string.IsNullOrWhiteSpace(input.AddUserName), x => x.AddUserName.Contains(input.AddUserName))
                .WhereIF(input.StartCreationTime != null && input.EndCreationTime != null,
                    x => x.AddTime >= input.StartCreationTime && x.AddTime <= input.EndCreationTime)
                .Select((x, b) =>
                    new GetXYZDQYLSQOutput()
                    {
                        InstanceNumber = x.InstanceNumber,
                        CreateTime = x.AddTime,
                        CreateTimeStr = x.AddTime != null ? x.AddTime.ToString(DateFormatHelper.DateTimeFormat) : "",
                        AddUserName = x.AddUserName,
                        OrderStatus = b.ProcessStatusName,
                        JfyyzyName = x.JfyyzyName,
                        RequestArrivalDate = x.RequestArrivalDate,
                        BusinessNo = x.BusinessNo,
                        BusinessName = x.BusinessName,
                        CustomerCode = x.CustomerCode,
                        CustomerName = x.CustomerName,
                        BigCustomerCode = x.BigCustomerCode,
                        BigCustomerName = x.BigCustomerName,
                        XSBName = x.XSBName,
                        XSYName = x.XSYName,
                        CostCentre = x.CostCentre,
                        CostCentreName = x.CostCentreName,
                        TotalCost = x.TotalCost,
                        TotalWeight = x.TotalWeight,
                        ApplicationReason = x.ApplicationReason,
                    }).MergeTable().Distinct().OrderBy(ins => ins.CreateTime, OrderByType.Desc);

            return listQueryable;
        }
        /// <summary>
        /// 查询数据
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<PagedResultDto<GetXYZDQYLSQOutput>> GetAllAsync(GetXYZDQYLSQInput input)
        {
            RefAsync<int> totalCount = 0;

            var listQueryable = GetQueryable(input);
            var listViewDto = await listQueryable.ToPageListAsync(input.PageIndex, input.PageSize, totalCount);

            var userId = await _iBPMPlatformApp.GetUserAsync(CurrentUser.UserName);

            listViewDto.ForEach(x => x.Url = _bPMUtilsApp.GetProcessUrl(x.InstanceNumber, userId));

            //返回结果
            return new PagedResultDto<GetXYZDQYLSQOutput>()
            {
                TotalCount = totalCount,
                Items = listViewDto
            };
        }

        /// <summary>
        /// 导出数据
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<List<GetXYZDQYLSQOutput>> ExportAsync(GetXYZDQYLSQInput input)
        {
            var listQueryable = GetQueryableExport(input);
            var listViewDto = await listQueryable.ToListAsync();
            return listViewDto;
        }
        #endregion
        #region 加急运输审批流程 报表
        /// <summary>
        /// 获取Queryable
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        private ISugarQueryable<GetJJYSSPNewOutput> GetQueryableExport(GetJJYSSPNewInput input)
        {
            var currentUserId = Guid.Empty;
            if (!input.IsQueryAll)
            {
                var currentUserDto = _dbPlatform.Queryable<Users>()
                    .Where(x => x.WorkNumber.Equals(CurrentUser.UserName)).First();
                if (currentUserDto != null)
                {
                    currentUserId = currentUserDto.UserId;
                }
            }
            var listQueryable = _db.Queryable<JJYSSPNewHeader, JJYSSPNewDetail, BusinessProcessesNew>(
                    (x, d, b) => new JoinQueryInfos(JoinType.Left, x.InstanceNumber == d.InstanceNumber, JoinType.Left, x.InstanceNumber == b.InstanceId))
                .Where(x=>x.FormType== "JJYSSPNew")
                .WhereIF(!string.IsNullOrWhiteSpace(input.InstanceNumber), x => x.InstanceNumber == input.InstanceNumber)
                .WhereIF(!input.IsQueryAll, x => x.AddUserId.Equals(currentUserId))
                .WhereIF(!input.OrderStatus.IsNullOrEmpty(), (x, d, b) => SqlFunc.ContainsArray(input.OrderStatus.ToArray(), b.ProcessStatusCode))
                .WhereIF(!string.IsNullOrWhiteSpace(input.AddUserName), x => x.AddUserName.Contains(input.AddUserName))
                .WhereIF(input.StartCreationTime != null && input.EndCreationTime != null,
                    x => x.AddTime >= input.StartCreationTime && x.AddTime <= input.EndCreationTime)
                .Select((x, d, b) =>
                    new GetJJYSSPNewOutput()
                    {
                        InstanceNumber = x.InstanceNumber,
                        CreateTime = x.AddTime,
                        CreateTimeStr = x.AddTime != null ? x.AddTime.ToString(DateFormatHelper.DateTimeFormat) : "",
                        AddUserName = x.AddUserName,
                        OrderStatus = b.ProcessStatusName,
                        JfyyzyName = x.JfyyzyName,
                        RequestArrivalDate = x.RequestArrivalDate,
                        BusinessNo = x.BusinessNo,
                        BusinessName = x.BusinessName,
                        CustomerCode =x.CustomerCode,
                        CustomerName = x.CustomerName,
                        BigCustomerCode =x.BigCustomerCode,
                        BigCustomerName = x.BigCustomerName,
                        XSBName =x.XSBName,
                        XSYName =x.XSYName,
                        CostCentre =x.CostCentre,
                        CostCentreName = x.CostCentreName,
                        TotalCost =x.TotalCost,
                        TotalWeight =x.TotalWeight,
                        ApplicationReason = x.ApplicationReason,
                        No = d.No,
                        DeliveryNoteNo =d.DeliveryNoteNo,
                        DeliveryAddress =d.DeliveryAddress,
                        Factory = d.Factory,
                        OutboundWeight =  d.OutboundWeight,
                        StandardShippingAmount = d.StandardShippingAmount,
                        ExpeditedShippingAmount= d.ExpeditedShippingAmount,
                        InvoiceAmount = d.InvoiceAmount,
                        TransportRatio =d.TransportRatio
                        
                    }).MergeTable().Distinct().OrderBy(ins => ins.CreateTime, OrderByType.Desc);

            return listQueryable;
        }

        /// <summary>
        /// 获取Queryable
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        private ISugarQueryable<GetJJYSSPNewOutput> GetQueryable(GetJJYSSPNewInput input)
        {
            var currentUserId = Guid.Empty;
            if (!input.IsQueryAll)
            {
                var currentUserDto = _dbPlatform.Queryable<Users>()
                    .Where(x => x.WorkNumber.Equals(CurrentUser.UserName)).First();
                if (currentUserDto != null)
                {
                    currentUserId = currentUserDto.UserId;
                }
            }
            var listQueryable = _db.Queryable<JJYSSPNewHeader, BusinessProcessesNew>(
                    (x, b) => new JoinQueryInfos(JoinType.Left, x.InstanceNumber == b.InstanceId))
                .Where(x => x.FormType == "JJYSSPNew")
                .WhereIF(!string.IsNullOrWhiteSpace(input.InstanceNumber), x => x.InstanceNumber == input.InstanceNumber)
                .WhereIF(!input.IsQueryAll, x => x.AddUserId.Equals(currentUserId))
                .WhereIF(!input.OrderStatus.IsNullOrEmpty(), (x, b) => SqlFunc.ContainsArray(input.OrderStatus.ToArray(), b.ProcessStatusCode))
                .WhereIF(!string.IsNullOrWhiteSpace(input.AddUserName), x => x.AddUserName.Contains(input.AddUserName))
                .WhereIF(input.StartCreationTime != null && input.EndCreationTime != null,
                    x => x.AddTime >= input.StartCreationTime && x.AddTime <= input.EndCreationTime)
                .Select((x, b) =>
                    new GetJJYSSPNewOutput()
                    {
                        InstanceNumber = x.InstanceNumber,
                        CreateTime = x.AddTime,
                        CreateTimeStr = x.AddTime != null ? x.AddTime.ToString(DateFormatHelper.DateTimeFormat) : "",
                        AddUserName = x.AddUserName,
                        OrderStatus = b.ProcessStatusName,
                        JfyyzyName = x.JfyyzyName,
                        RequestArrivalDate = x.RequestArrivalDate,
                        BusinessNo = x.BusinessNo,
                        BusinessName = x.BusinessName,
                        CustomerCode = x.CustomerCode,
                        CustomerName = x.CustomerName,
                        BigCustomerCode = x.BigCustomerCode,
                        BigCustomerName = x.BigCustomerName,
                        XSBName = x.XSBName,
                        XSYName = x.XSYName,
                        CostCentre = x.CostCentre,
                        CostCentreName = x.CostCentreName,
                        TotalCost = x.TotalCost,
                        TotalWeight = x.TotalWeight,
                        ApplicationReason = x.ApplicationReason,
                    }).MergeTable().Distinct().OrderBy(ins => ins.CreateTime, OrderByType.Desc);

            return listQueryable;
        }
        /// <summary>
        /// 查询数据
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<PagedResultDto<GetJJYSSPNewOutput>> GetAllAsync(GetJJYSSPNewInput input)
        {
            RefAsync<int> totalCount = 0;

            var listQueryable = GetQueryable(input);
            var listViewDto = await listQueryable.ToPageListAsync(input.PageIndex, input.PageSize, totalCount);

            var userId = await _iBPMPlatformApp.GetUserAsync(CurrentUser.UserName);

            listViewDto.ForEach(x => x.Url = _bPMUtilsApp.GetProcessUrl(x.InstanceNumber, userId));

            //返回结果
            return new PagedResultDto<GetJJYSSPNewOutput>()
            {
                TotalCount = totalCount,
                Items = listViewDto
            };
        }

        /// <summary>
        /// 导出数据
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<List<GetJJYSSPNewOutput>> ExportAsync(GetJJYSSPNewInput input)
        {
            var listQueryable = GetQueryable(input);
            var listViewDto = await listQueryable.ToListAsync();
            return listViewDto;
        }
        #endregion
        #region 产品提前备货 报表

        /// <summary>
        /// 获取Queryable
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        private ISugarQueryable<GetCPTQBHOutput> GetQueryable(GetCPTQBHInput input)
        {
            var currentUserId = Guid.Empty;
            if (!input.IsQueryAll)
            {
                var currentUserDto = _dbPlatform.Queryable<Users>()
                    .Where(x => x.WorkNumber.Equals(CurrentUser.UserName)).First();
                if (currentUserDto != null)
                {
                    currentUserId = currentUserDto.UserId;
                }
            }
            var listQueryable = _db.Queryable<CPTQBHHeader, CPTQBHDetail, BusinessProcessesNew>(
                    (x, d, b) => new JoinQueryInfos(JoinType.Left, x.InstanceNumber == d.InstanceNumber, JoinType.Left, x.InstanceNumber == b.InstanceId))
                .WhereIF(!string.IsNullOrWhiteSpace(input.InstanceNumber), x => x.InstanceNumber == input.InstanceNumber)
                .WhereIF(!input.IsQueryAll, x => x.AddUserId.Equals(currentUserId))
                .WhereIF(!input.OrderStatus.IsNullOrEmpty(), (x, d, b) => SqlFunc.ContainsArray(input.OrderStatus.ToArray(), b.ProcessStatusCode))
                .WhereIF(!string.IsNullOrWhiteSpace(input.AddUserName), x => x.AddUserName.Contains(input.AddUserName))
                .WhereIF(input.StartCreationTime != null && input.EndCreationTime != null,
                    x => x.AddTime >= input.StartCreationTime && x.AddTime <= input.EndCreationTime)
                .Select((x, d, b) =>
                    new GetCPTQBHOutput()
                    {
                        InstanceNumber = x.InstanceNumber,
                        CreateTime = x.AddTime,
                        CreateTimeStr = x.AddTime != null ? x.AddTime.ToString(DateFormatHelper.DateTimeFormat) : "",
                        AddUserName = x.AddUserName,
                        OrderStatus = b.ProcessStatusName,
                        SalesDepartment = x.SalesDepartment,
                        SalesDivision = x.SalesDivision,
                        SalesCompany = x.SalesCompany,
                        SalesArea = x.SalesArea,
                        OperationCenter = x.OperationCenter,
                        Factory = x.Factory,
                        FactoryDes = x.FactoryDes,
                        CustomerNo = x.CustomerNo,
                        CustomerName = x.CustomerName,
                        CustomerAddress = x.CustomerAddress,
                        CustomerType = x.CustomerType,
                        Reason = x.Reason,
                        TJApply = x.TJApply,
                        XYApply = x.XYApply,
                        Debt = x.Debt,
                        Arrears = x.Arrears,
                        TotalPrice = x.TotalPrice,
                        Remark = x.Remark,
                        SortNo = d.SortNo,
                        BusinessNo = d.BusinessNo,
                        ProjectName = d.ProjectName,
                        ProjectAddress = d.ProjectAddress,
                        ProductType = d.ProductType,
                        StockStage = d.StockStage,
                        Material = d.Material,
                        MaterialDesc = d.MaterialDesc,
                        Rename = d.Rename,
                        DependencyNo = d.DependencyNo,
                        ColorNumber = d.ColorNumber,
                        Pack = d.Pack,
                        Price = d.Price,
                        Requirement = d.Requirement,
                        TotalStock = d.TotalStock,
                        SellNumber1 = d.SellNumber1,
                        SellMonth1 = d.SellMonth1,
                        SellNumber2 = d.SellNumber2,
                        SellMonth2 = d.SellMonth2,
                        SellMonth3 = d.SellMonth3,
                        SellNumber3 = d.SellNumber3
                    }).MergeTable().Distinct().OrderBy(ins => ins.CreateTime, OrderByType.Desc);

            return listQueryable;
        }

        /// <summary>
        /// 查询数据
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<PagedResultDto<GetCPTQBHOutput>> GetAllAsync(GetCPTQBHInput input)
        {
            RefAsync<int> totalCount = 0;

            var listQueryable = GetQueryable(input);
            var listViewDto = await listQueryable.ToPageListAsync(input.PageIndex, input.PageSize, totalCount);

            var userId = await _iBPMPlatformApp.GetUserAsync(CurrentUser.UserName);

            listViewDto.ForEach(x => x.Url = _bPMUtilsApp.GetProcessUrl(x.InstanceNumber, userId));

            //返回结果
            return new PagedResultDto<GetCPTQBHOutput>()
            {
                TotalCount = totalCount,
                Items = listViewDto
            };
        }

        /// <summary>
        /// 导出数据
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<List<GetCPTQBHOutput>> ExportAsync(GetCPTQBHInput input)
        {
            var listQueryable = GetQueryable(input);
            var listViewDto = await listQueryable.ToListAsync();
            return listViewDto;
        }

        #endregion

        #region 见单生产报表

        /// <summary>
        /// 获取Queryable
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        private ISugarQueryable<ExportJDSCOutput> GetQueryable(GetJDSCInput input)
        {
            var listQueryable = _db.Queryable<JDSCApply, JDSCApplyLine, BusinessProcessesNew>(
                    (j, jl, bu) => new JoinQueryInfos(
                        JoinType.Inner, j.ID == jl.MainID,
                        JoinType.Left, j.InstanceId == bu.InstanceId))
                .WhereIF(!string.IsNullOrWhiteSpace(input.InstanceNumber),
                    (j, jl, bu) => j.InstanceId.Contains(input.InstanceNumber))
                .WhereIF(!input.OrderStatus.IsNullOrEmpty(),
                    (j, jl, bu) => SqlFunc.ContainsArray<string>(input.OrderStatus.ToArray(), bu.ProcessStatusCode))
                .WhereIF(!string.IsNullOrWhiteSpace(input.AddUserName),
                    j => j.ProcessStartUserName.Equals(input.AddUserName))
                .WhereIF(input.StartCreationTime != null && input.EndCreationTime != null,
                    j => j.ProcessStartTime >= input.StartCreationTime && j.ProcessStartTime <= input.EndCreationTime)
                .Select((j, jl, bu) =>
                    new ExportJDSCOutput()
                    {
                        InstanceNumber = j.InstanceId,
                        ProcessStartTime = j.ProcessStartTime,
                        ProcessStartUserName = j.ProcessStartUserName,
                        OrderStatus = bu.ProcessStatusName,
                        SalesalespersonUserName = j.SalesalespersonUserName,
                        CustomerCode = j.CustomerCode,
                        CustomerName = j.CustomerName,
                        BusinessOpportunityNo = j.BusinessOpportunityNo,
                        ProjectName = j.ProjectName,
                        ProjectContinuTime = j.ProjectContinuTime,
                        ApplyReason = j.ApplyReason,
                        MaterialName = jl.MaterialName,
                        ColorNumber = jl.ColorNumber,
                        PackSpecifications = jl.PackSpecifications,
                        Quantity = jl.Quantity
                    }).MergeTable().Distinct().OrderBy(ins => ins.ProcessStartTime, OrderByType.Desc);

            return listQueryable;
        }

        /// <summary>
        /// 查询数据
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<PagedResultDto<GetJDSCOutput>> GetAllAsync(GetJDSCInput input)
        {
            RefAsync<int> totalCount = 0;

            var listQueryable = GetQueryable(input);
            var listViewDto = await listQueryable.ToPageListAsync(input.PageIndex, input.PageSize, totalCount);

            var userId = await _iBPMPlatformApp.GetUserAsync(CurrentUser.UserName);

            listViewDto.ForEach(x => x.Url = _bPMUtilsApp.GetProcessUrl(x.InstanceNumber, userId));

            var list = listViewDto.Select(j => new GetJDSCOutput()
            {
                InstanceNumber = j.InstanceNumber,
                ProcessStartTime = j.ProcessStartTime,
                ProcessStartUserName = j.ProcessStartUserName,
                OrderStatus = j.OrderStatus,
                CustomerCode = j.CustomerCode,
                BusinessOpportunityNo = j.BusinessOpportunityNo,
                Url = j.Url
            }).Distinct().ToList();

            //返回结果
            return new PagedResultDto<GetJDSCOutput>()
            {
                TotalCount = totalCount,
                Items = list
            };
        }

        /// <summary>
        /// 导出数据
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<List<ExportJDSCOutput>> ExportAsync(GetJDSCInput input)
        {
            var listQueryable = GetQueryable(input);
            var listViewDto = await listQueryable.ToListAsync();
            return listViewDto;
        }

        #endregion

        #region 工程取消订单报表

        /// <summary>
        /// 获取Queryable
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        private ISugarQueryable<GetGCCancelOrderOutput> GetQueryable(GetGCCancelOrderInput input)
        {
            var listQueryable = _db.Queryable<GCCancelOrderHead, GCCancelOrderDetails, BusinessProcessesNew>(
                    (j, jl, bu) => new JoinQueryInfos(
                        JoinType.Inner, j.InstanceId == jl.InstanceId,
                        JoinType.Left, j.InstanceId == bu.InstanceId))
                .WhereIF(!string.IsNullOrWhiteSpace(input.InstanceNumber),
                    (j, jl, bu) => j.InstanceId.Contains(input.InstanceNumber))
                .WhereIF(!input.OrderStatus.IsNullOrEmpty(),
                    (j, jl, bu) => SqlFunc.ContainsArray<string>(input.OrderStatus.ToArray(), bu.ProcessStatusCode))
                .WhereIF(!string.IsNullOrWhiteSpace(input.AddUserName), j => j.AddUserName.Equals(input.AddUserName))
                .WhereIF(input.StartCreationTime != null && input.EndCreationTime != null,
                    j => j.AddTime >= input.StartCreationTime && j.AddTime <= input.EndCreationTime).Select(
                    (j, jl, bu) =>
                        new GetGCCancelOrderOutput()
                        {
                            InstanceNumber = j.InstanceId,
                            AddTime = j.AddTime,
                            AddUserName = j.AddUserName,
                            OrderStatus = bu.ProcessStatusName,
                            SellUserName = j.SellUserName,
                            EAssistantNumber = j.EAssistantNumber,
                            CompanyCode = j.CompanyCode,
                            CustomerCode = j.CustomerCode,
                            CustomerName = j.CustomerName,
                            OpportunityNumber = j.OpportunityNumber,
                            ProjectName = j.ProjectName,
                            ReasonClassification = j.ReasonClassification,
                            Reason = j.Reason,
                            MaterialCode = jl.MaterialCode,
                            MaterialName = jl.MaterialName,
                            CancelQuantity = jl.CancelQuantity,
                            CancelATotalAmount = jl.CancelATotalAmount,
                            CancelInvoicingTotalAmount = jl.CancelInvoicingTotalAmount,
                            OrderDate = jl.OrderDate,
                            Status = jl.Status,
                            SluggishAmount = jl.SluggishAmount,
                            SluggishQuantity = jl.SluggishQuantity,
                            SluggishProductBatch = jl.SluggishProductBatch,
                            SluggishSolution = jl.SluggishSolution,
                            SluggishCompletionDate = jl.SluggishCompletionDate,
                            FineType = jl.FineType,
                            FineAmount = jl.FineAmount,
                            RestructuringCost = jl.RestructuringCost
                        }).MergeTable().Distinct().OrderBy(ins => ins.AddTime, OrderByType.Desc);

            return listQueryable;
        }

        /// <summary>
        /// 查询数据
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<PagedResultDto<GetGCCancelOrderOutput>> GetAllAsync(GetGCCancelOrderInput input)
        {
            RefAsync<int> totalCount = 0;

            var listQueryable = GetQueryable(input);
            var listViewDto = await listQueryable.ToPageListAsync(input.PageIndex, input.PageSize, totalCount);

            var userId = await _iBPMPlatformApp.GetUserAsync(CurrentUser.UserName);

            listViewDto.ForEach(x => x.Url = _bPMUtilsApp.GetProcessUrl(x.InstanceNumber, userId));

            //返回结果
            return new PagedResultDto<GetGCCancelOrderOutput>()
            {
                TotalCount = totalCount,
                Items = listViewDto
            };
        }

        /// <summary>
        /// 导出数据
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<List<GetGCCancelOrderOutput>> ExportAsync(GetGCCancelOrderInput input)
        {
            var listQueryable = GetQueryable(input);
            var listViewDto = await listQueryable.ToListAsync();
            return listViewDto;
        }

        #endregion

        #region 加急运输&小于最低起运量运输报表

        /// <summary>
        /// 获取Queryable
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        private ISugarQueryable<GetExpeditedTransportOutput> GetQueryable(GetExpeditedTransportInput input)
        {
            var listQueryable = _db
                .Queryable<ExpeditedTransportation, ExpeditedTransportationDetail, BusinessProcessesNew>(
                    (j, jl, bu) => new JoinQueryInfos(
                        JoinType.Inner, j.InstanceNumber == jl.InstanceNumber,
                        JoinType.Left, j.InstanceNumber == bu.InstanceId))
                .WhereIF(!string.IsNullOrWhiteSpace(input.InstanceNumber),
                    (j, jl, bu) => j.InstanceNumber.Contains(input.InstanceNumber))
                .WhereIF(!input.OrderStatus.IsNullOrEmpty(),
                    (j, jl, bu) => SqlFunc.ContainsArray<string>(input.OrderStatus.ToArray(), bu.ProcessStatusCode))
                .WhereIF(!string.IsNullOrWhiteSpace(input.AddUserName), j => j.UserName.Equals(input.AddUserName))
                .WhereIF(input.StartCreationTime != null && input.EndCreationTime != null,
                    j => j.CreateTime >= input.StartCreationTime && j.CreateTime <= input.EndCreationTime).Select(
                    (j, jl, bu) =>
                        new GetExpeditedTransportOutput()
                        {
                            InstanceNumber = j.InstanceNumber,
                            UserName = j.UserName,
                            OrderStatus = bu.ProcessStatusName,
                            CreateTime = j.CreateTime,
                            ApplicationType = j.ApplicationType,
                            Sales = j.Sales,
                            LandingCompany = j.LandingCompany,
                            ShippingFactory = j.ShippingFactory,
                            CustomerCode = j.CustomerCode,
                            CustomerName = j.CustomerName,
                            OpportunityNumber = j.OpportunityNumber,
                            ProjectName = j.ProjectName,
                            DeliveryAddress = j.DeliveryAddress,
                            TotalFreightDifference = j.TotalFreightDifference,
                            Reason = j.Reason,
                            ProductCategory = j.ProductCategory,
                            CostCenter = j.CostCenter,
                            ApplicationReason = j.ApplicationReason,
                            RequestArrivalTime = jl.RequestArrivalTime,
                            DeliveryNoteNo = jl.DeliveryNoteNo,
                            OutboundWeight = jl.OutboundWeight,
                            StandardShippingAmount = jl.StandardShippingAmount,
                            ExpeditedShippingAmount = jl.ExpeditedShippingAmount,
                            InvoiceAmount = jl.InvoiceAmount,
                            TransportRatio = jl.TransportRatio
                        }).MergeTable().Distinct().OrderBy(ins => ins.CreateTime, OrderByType.Desc);

            return listQueryable;
        }

        /// <summary>
        /// 查询数据
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<PagedResultDto<GetExpeditedTransportOutput>> GetAllAsync(GetExpeditedTransportInput input)
        {
            RefAsync<int> totalCount = 0;

            var listQueryable = GetQueryable(input);
            var listViewDto = await listQueryable.ToPageListAsync(input.PageIndex, input.PageSize, totalCount);

            var userId = await _iBPMPlatformApp.GetUserAsync(CurrentUser.UserName);

            listViewDto.ForEach(x => x.Url = _bPMUtilsApp.GetProcessUrl(x.InstanceNumber, userId));

            //返回结果
            return new PagedResultDto<GetExpeditedTransportOutput>()
            {
                TotalCount = totalCount,
                Items = listViewDto
            };
        }

        /// <summary>
        /// 导出数据
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<List<GetExpeditedTransportOutput>> ExportAsync(GetExpeditedTransportInput input)
        {
            var listQueryable = GetQueryable(input);
            var listViewDto = await listQueryable.ToListAsync();
            return listViewDto;
        }

        #endregion

        #region 秀珀工程项目审批流程

        private ISugarQueryable<GetXZGCXMSPLCHeaderOutPut> GetQueryable(GetXZGCXMSPLCHeaderInput input)
        {
            var currentUserId = Guid.Empty;
            if (!input.IsQueryAll)
            {
                var currentUserDto = _dbPlatform.Queryable<Users>()
                    .Where(x => x.WorkNumber.Equals(CurrentUser.UserName)).First();
                if (currentUserDto != null)
                {
                    currentUserId = currentUserDto.UserId;
                }
            }

            var listQueryable = _db.Queryable<XZGCXMSPLCHeader, BusinessProcessesNew>(
                    (x, b) => new JoinQueryInfos(JoinType.Left, x.InstanceNumber == b.InstanceId)
                )
                .WhereIF(!input.IsQueryAll, x => x.AddUserId.Equals(currentUserId))
                .WhereIF(!string.IsNullOrWhiteSpace(input.InstanceNumber),
                    x => x.InstanceNumber == input.InstanceNumber)
                .WhereIF(!input.OrderStatus.IsNullOrEmpty(),
                    (x, b) => SqlFunc.ContainsArray<string>(input.OrderStatus.ToArray(), b.ProcessStatusCode))
                .WhereIF(!string.IsNullOrWhiteSpace(input.Title), x => x.Title.Equals(input.Title))
                .WhereIF(!string.IsNullOrWhiteSpace(input.AddUserName), x => x.AddUserName.Equals(input.AddUserName))
                .WhereIF(!string.IsNullOrWhiteSpace(input.BusinessOpportunityNo),
                    x => x.BusinessOpportunityNo.Contains(input.BusinessOpportunityNo))
                .WhereIF(!string.IsNullOrWhiteSpace(input.BusinessOpportunityName),
                    x => x.BusinessOpportunityName.Contains(input.BusinessOpportunityName))
                .WhereIF(!string.IsNullOrWhiteSpace(input.CompanyName), x => x.CompanyName.Contains(input.CompanyName))
                .WhereIF(!string.IsNullOrWhiteSpace(input.AreaName), x => x.AreaName.Contains(input.AreaName))
                .WhereIF(!string.IsNullOrWhiteSpace(input.Sales), x => x.Sales.Contains(input.Sales))
                .WhereIF(input.StartCreationTime != null && input.EndCreationTime != null,
                    x => x.AddTime >= input.StartCreationTime && x.AddTime <= input.EndCreationTime)
                .Select((x, b) => new GetXZGCXMSPLCHeaderOutPut
                {
                    AreaName = x.AreaName,
                    BusinessOpportunityName = x.BusinessOpportunityName,
                    BusinessOpportunityNo = x.BusinessOpportunityNo,
                    CompanyName = x.CompanyName,
                    Content = x.Content,
                    InstanceNumber = x.InstanceNumber,
                    ProcessStartTime = x.AddTime,
                    ProcessStartUserName = x.AddUserName,
                    OrderStatus = b.ProcessStatusName,
                    Sales = x.Sales,
                    Title = x.Title,
                }).MergeTable().Distinct().OrderBy(ins => ins.ProcessStartTime, OrderByType.Desc);
            // var sql = listQueryable.ToSql().Key;
            return listQueryable;
        }

        public async Task<PagedResultDto<GetXZGCXMSPLCHeaderOutPut>> GetAllAsync(GetXZGCXMSPLCHeaderInput input)
        {
            RefAsync<int> totalCount = 0;

            var listQueryable = GetQueryable(input);
            var listViewDto = await listQueryable.ToPageListAsync(input.PageIndex, input.PageSize, totalCount);

            var userId = await _iBPMPlatformApp.GetUserAsync(CurrentUser.UserName);

            listViewDto.ForEach(x => x.Url = _bPMUtilsApp.GetProcessUrl(x.InstanceNumber, userId));

            //返回结果
            return new PagedResultDto<GetXZGCXMSPLCHeaderOutPut>()
            {
                TotalCount = totalCount,
                Items = listViewDto
            };
        }

        public async Task<List<GetXZGCXMSPLCHeaderOutPut>> ExportAsync(GetXZGCXMSPLCHeaderInput input)
        {
            var listQueryable = GetQueryable(input);
            var listViewDto = await listQueryable.ToListAsync();
            return listViewDto;
        }

        #endregion

        #region 订单非首选工厂申请

        public async Task<PagedResultDto<GetDDFSXGCApplyOutput>> GetAllAsync(GetDDFSXGCApplyInput input)
        {
            RefAsync<int> totalCount = 0;

            var listQueryable = GetQueryable(input);
            var listViewDto = await listQueryable.ToPageListAsync(input.PageIndex, input.PageSize, totalCount);

            var userId = await _iBPMPlatformApp.GetUserAsync(CurrentUser.UserName);

            listViewDto.ForEach(x => x.Url = _bPMUtilsApp.GetProcessUrl(x.InstanceNumber, userId));

            //返回结果
            return new PagedResultDto<GetDDFSXGCApplyOutput>()
            {
                TotalCount = totalCount,
                Items = listViewDto
            };
        }

        public async Task<List<GetDDFSXGCApplyOutput>> ExportAsync(GetDDFSXGCApplyInput input)
        {
            var listQueryable = GetQueryable(input);
            var listViewDto = await listQueryable.ToListAsync();
            return listViewDto;
        }


        private ISugarQueryable<GetDDFSXGCApplyOutput> GetQueryable(GetDDFSXGCApplyInput input)
        {
            // throw new NotImplementedException();

            var currentUserId = Guid.Empty;
            if (!input.IsQueryAll)
            {
                var currentUserDto = _dbPlatform.Queryable<Users>()
                    .Where(x => x.WorkNumber.Equals(CurrentUser.UserName)).First();
                if (currentUserDto != null)
                {
                    currentUserId = currentUserDto.UserId;
                }
            }

            var listQueryable = _db.Queryable<DDFSXGCApply, BusinessProcessesNew>(
                    (x, b) => new JoinQueryInfos(JoinType.Left, x.InstanceId == b.InstanceId)
                ).WhereIF(!input.IsQueryAll, x => x.ProcessStartUserId.Equals(currentUserId))
                .WhereIF(!string.IsNullOrWhiteSpace(input.InstanceNumber), x => x.InstanceId == input.InstanceNumber)
                .WhereIF(!input.OrderStatus.IsNullOrEmpty(),
                    (x, b) => SqlFunc.ContainsArray(input.OrderStatus.ToArray(), b.ProcessStatusCode))
                .WhereIF(!string.IsNullOrWhiteSpace(input.AddUserName),
                    (x, b) => b.StartUserName.Contains(input.AddUserName))
                .WhereIF(input.StartCreationTime != null && input.EndCreationTime != null,
                    (x, b) => b.StartTime >= input.StartCreationTime &&
                              b.StartTime <= input.EndCreationTime)
                .WhereIF(!string.IsNullOrWhiteSpace(input.SalesalespersonUserName), (x, b) =>
                    x.SalesalespersonUserName == input.SalesalespersonUserName)
                .WhereIF(!string.IsNullOrWhiteSpace(input.CustomerCode), (x, b) =>
                    x.CustomerCode == input.CustomerCode)
                .WhereIF(!string.IsNullOrWhiteSpace(input.CustomerName), (x, b) =>
                    x.CustomerName == input.CustomerName)
                .WhereIF(!string.IsNullOrWhiteSpace(input.BusinessOpportunityNo), (x, b) =>
                    x.BusinessOpportunityNo == input.BusinessOpportunityNo)
                .WhereIF(!string.IsNullOrWhiteSpace(input.ProjectName), (x, b) =>
                    x.ProjectName == input.ProjectName)
                .WhereIF(!string.IsNullOrWhiteSpace(input.FirstFactoryCode), (x, b) =>
                    x.FirstFactoryCode == input.FirstFactoryCode)
                .Select((x, b) => new GetDDFSXGCApplyOutput
                {
                    UserName = b.StartUserName,
                    InstanceNumber = x.InstanceId,
                    OrderStatus = b.ProcessStatusName,
                    CreateTime = b.StartTime.ToString(),
                    SalesalespersonUserName = x.SalesalespersonUserName,
                    ApplyReason = x.ApplyReason,
                    BelongArea = x.BelongArea,
                    BusinessOpportunityNo = x.BusinessOpportunityNo,
                    CustomerCode = x.CustomerCode,
                    CustomerName = x.CustomerName,
                    FirstFactoryCode = x.FirstFactoryCode,
                    FirstFactoryContact = x.FirstFactoryContact,
                    FirstFactoryName = x.FirstFactoryName,
                    FirstFactoryTel = x.FirstFactoryTel,
                    OrderFactoryCode = x.OrderFactoryCode,
                    OrderFactoryName = x.OrderFactoryName,
                    ProjectName = x.ProjectName,
                    ReasonCategory = x.ReasonCategory,
                });

            return listQueryable;
        }

        #endregion

        #region 一体板订单取消变更

        public async Task<PagedResultDto<GetYTBOrderOutput>> GetAllAsync(GetYTBOrderInput input)
        {
            RefAsync<int> totalCount = 0;

            var listQueryable = GetQueryable(input);
            var listViewDto = await listQueryable.ToPageListAsync(input.PageIndex, input.PageSize, totalCount);

            var userId = await _iBPMPlatformApp.GetUserAsync(CurrentUser.UserName);

            listViewDto.ForEach(x => x.Url = _bPMUtilsApp.GetProcessUrl(x.InstanceNumber, userId));

            //返回结果
            return new PagedResultDto<GetYTBOrderOutput>()
            {
                TotalCount = totalCount,
                Items = listViewDto
            };
        }

        public async Task<List<GetYTBOrderOutput>> ExportAsync(GetYTBOrderInput input)
        {
            var listQueryable = GetQueryable(input);
            var listViewDto = await listQueryable.ToListAsync();
            return listViewDto;
        }

        private ISugarQueryable<GetYTBOrderOutput> GetQueryable(GetYTBOrderInput input)
        {
            var currentUserId = Guid.Empty;
            if (!input.IsQueryAll)
            {
                var currentUserDto = _dbPlatform.Queryable<Users>()
                    .Where(x => x.WorkNumber.Equals(CurrentUser.UserName)).First();
                if (currentUserDto != null)
                {
                    currentUserId = currentUserDto.UserId;
                }
            }

            var listQueryable = _db.Queryable<YTBOrder, BusinessProcessesNew>(
                    (x, b) => new JoinQueryInfos(JoinType.Left, x.InstanceId == b.InstanceId)
                ).WhereIF(!input.IsQueryAll, x => x.ProcessStartUserId.Equals(currentUserId))
                .WhereIF(!string.IsNullOrWhiteSpace(input.InstanceNumber), x => x.InstanceId == input.InstanceNumber)
                .WhereIF(!input.OrderStatus.IsNullOrEmpty(),
                    (x, b) => SqlFunc.ContainsArray(input.OrderStatus.ToArray(), b.ProcessStatusCode))
                .WhereIF(!string.IsNullOrWhiteSpace(input.AddUserName),
                    (x, b) => b.StartUserName.Contains(input.AddUserName))
                .WhereIF(input.StartCreationTime != null && input.EndCreationTime != null,
                    (x, b) => b.StartTime >= input.StartCreationTime &&
                              b.StartTime <= input.EndCreationTime)
                .WhereIF(!string.IsNullOrWhiteSpace(input.ProjectCode), (x, b) =>
                    x.ProjectCode == input.ProjectCode)
                .WhereIF(!string.IsNullOrWhiteSpace(input.ProjectName), (x, b) =>
                    x.ProjectName == input.ProjectName)
                .WhereIF(!string.IsNullOrWhiteSpace(input.Salearea), (x, b) =>
                    x.Salearea == input.Salearea)
                .WhereIF(!string.IsNullOrWhiteSpace(input.Salername), (x, b) =>
                    x.Salername == input.Salername)
                .WhereIF(!string.IsNullOrWhiteSpace(input.Customercode), (x, b) =>
                    x.Customercode == input.Customercode)
                .WhereIF(!string.IsNullOrWhiteSpace(input.Customername), (x, b) =>
                    x.Customername == input.Customername)
                .WhereIF(!string.IsNullOrWhiteSpace(input.Ordernumber), (x, b) =>
                    x.Ordernumber == input.Ordernumber)
                .WhereIF(!string.IsNullOrWhiteSpace(input.Factory), (x, b) =>
                    x.Factory == input.Factory)
                .WhereIF(!string.IsNullOrWhiteSpace(input.Factoryname), (x, b) =>
                    x.Factoryname == input.Factoryname)
                .WhereIF(!string.IsNullOrWhiteSpace(input.Ddqxreasontypename), (x, b) =>
                    x.Ddqxreasontypename == input.Ddqxreasontypename)
                .WhereIF(!string.IsNullOrWhiteSpace(input.Sqqxtotal), (x, b) =>
                    x.Sqqxtotal == input.Sqqxtotal)
                .Select((x, b) => new GetYTBOrderOutput()
                {
                    UserName = b.StartUserName,
                    InstanceNumber = x.InstanceId,
                    OrderStatus = b.ProcessStatusName,
                    CreateTime = b.StartTime.ToString(),
                    ProjectName = x.ProjectName,
                    Cbqrhandleway = x.Cbqrhandleway,
                    Closingfeedback = x.Closingfeedback,
                    Costbearingparty = x.Costbearingparty,
                    Costcenter = x.Costcenter,
                    Customercode = x.Customercode,
                    Customername = x.Customername,
                    Ddcancelreason = x.Ddcancelreason,
                    Ddqxreasontypename = x.Ddqxreasontypename,
                    Factory = x.Factory,
                    Factoryname = x.Factoryname,
                    Ordernumber = x.Ordernumber,
                    Price = x.Price,
                    ProjectCode = x.ProjectCode,
                    Salearea = x.Salearea,
                    Salername = x.Salername,
                    Sfcsextraprice = x.Sfcsextraprice,
                    Sqqxtotal = x.Sqqxtotal
                });
            return listQueryable;
        }

        #endregion

        #region 新工程取消订单流程

        public async Task<PagedResultDto<GetEngineeringBatchCancelOrdersOutput>> GetAllAsync(
            GetEngineeringBatchCancelOrdersInput input)
        {
            RefAsync<int> totalCount = 0;

            var listQueryable = GetQueryable(input);
            var listViewDto = await listQueryable.ToPageListAsync(input.PageIndex, input.PageSize, totalCount);

            var userId = await _iBPMPlatformApp.GetUserAsync(CurrentUser.UserName);

            listViewDto.ForEach(x =>
            {
                x.Url = _bPMUtilsApp.GetProcessUrl(x.InstanceNumber, userId);
                x.UserNumber = _iBPMPlatformApp.GetUserNumberAsync(x.AddUserId);//新增创建人工号
                x.OrderStatus = x.IsEnd == true ? x.OrderStatus : "待审批";
            });
            //返回结果
            return new PagedResultDto<GetEngineeringBatchCancelOrdersOutput>()
            {
                TotalCount = totalCount,
                Items = listViewDto
            };
        }

        public async Task<List<GetEngineeringBatchCancelOrdersOutput>> ExportAsync(
            GetEngineeringBatchCancelOrdersInput input)
        {
            var listQueryable = GetQueryableToExel(input);
            var listViewDto = await listQueryable.ToListAsync();
            listViewDto.ForEach(x =>
            {
                x.UserNumber = _iBPMPlatformApp.GetUserNumberAsync(x.AddUserId);//新增创建人工号
                x.OrderStatus = x.IsEnd == true ? x.OrderStatus : "待审批";
            });
            return listViewDto;
        }

        private ISugarQueryable<GetEngineeringBatchCancelOrdersOutput> GetQueryable(
            GetEngineeringBatchCancelOrdersInput input)
        {
            var currentUserId = Guid.Empty;
            if (!input.IsQueryAll)
            {
                var currentUserDto = _dbPlatform.Queryable<Users>()
                    .Where(x => x.WorkNumber.Equals(CurrentUser.UserName)).First();
                if (currentUserDto != null)
                {
                    currentUserId = currentUserDto.UserId;
                }
            }

            var listQueryable = _db.Queryable<EngineeringBatchCancelOrdersHeader, BusinessProcessesNew>(
                    (x, b) => new JoinQueryInfos(JoinType.Left, x.InstanceNumber == b.InstanceId)
                ).WhereIF(!input.IsQueryAll, x => x.AddUserId.Equals(currentUserId))
                .WhereIF(!string.IsNullOrWhiteSpace(input.InstanceNumber),
                    x => x.InstanceNumber == input.InstanceNumber)
                .WhereIF(!input.OrderStatus.IsNullOrEmpty(),
                    (x, b) => SqlFunc.ContainsArray(input.OrderStatus.ToArray(), b.ProcessStatusCode))
                .WhereIF(!string.IsNullOrWhiteSpace(input.AddUserName),
                    (x, b) => x.AddUserName.Contains(input.AddUserName))
                .WhereIF(input.StartCreationTime != null && input.EndCreationTime != null,
                    (x, b) => b.StartTime >= input.StartCreationTime &&
                              b.StartTime <= input.EndCreationTime)
                .WhereIF(!string.IsNullOrWhiteSpace(input.OrderCenter), (x, b) =>
                    x.OrderCenter == input.OrderCenter)
                .WhereIF(!string.IsNullOrWhiteSpace(input.CancelReason), (x, b) =>
                    x.CancelReason == input.CancelReason)
                .WhereIF(!string.IsNullOrWhiteSpace(input.SellUserName), (x, b) =>
                    x.SellUserName == input.SellUserName)
                .WhereIF(!string.IsNullOrWhiteSpace(input.ReasonClassification), (x, b) =>
                    x.ReasonClassification == input.ReasonClassification)
                .WhereIF(!string.IsNullOrWhiteSpace(input.IsProductionFees), (x, b) =>
                    x.IsProductionFees == input.IsProductionFees)
                .WhereIF(!string.IsNullOrWhiteSpace(input.SalesOrganization), (x, b) =>
                    x.SalesOrganization == input.SalesOrganization)
                .WhereIF(!string.IsNullOrWhiteSpace(input.CostCenterCredit), (x, b) =>
                    x.CostCenterCredit == input.CostCenterCredit)
                .WhereIF(!string.IsNullOrWhiteSpace(input.IsNeedInvoice), (x, b) =>
                    x.IsNeedInvoice == input.IsNeedInvoice)
                .WhereIF(!string.IsNullOrWhiteSpace(input.InvoiceTitle), (x, b) =>
                    x.InvoiceTitle == input.InvoiceTitle)
                .WhereIF(!string.IsNullOrWhiteSpace(input.Division), (x, b) =>
                    x.Division == input.Division)
                .Select((x, b) => new GetEngineeringBatchCancelOrdersOutput()
                {
                    UserName = x.AddUserName,
                    AddUserId = x.AddUserId,
                    InstanceNumber = x.InstanceNumber,
                    OrderStatus = b.ProcessStatusName,
                    CreateTime = b.StartTime.ToString(),
                    CancelReason = x.CancelReason,
                    CostCenterCredit = x.CostCenterCredit,
                    InvoiceTitle = x.InvoiceTitle,
                    IsNeedInvoice = x.IsNeedInvoice,
                    IsProductionFees = x.IsProductionFees,
                    OrderCenter = x.OrderCenter,
                    ReasonClassification = x.ReasonClassification,
                    Remark = x.Remark,
                    SalesOrganization = x.SalesOrganization,
                    SellUserName = x.SellUserName,
                    Division = x.Division,
                    IsEnd = b.IsEnd
                }).MergeTable().Distinct().OrderBy(ins => ins.InstanceNumber, OrderByType.Desc);
            return listQueryable;
        }
        private ISugarQueryable<GetEngineeringBatchCancelOrdersOutput> GetQueryableToExel(
           GetEngineeringBatchCancelOrdersInput input)
        {
            var currentUserId = Guid.Empty;
            if (!input.IsQueryAll)
            {
                var currentUserDto = _dbPlatform.Queryable<Users>()
                    .Where(x => x.WorkNumber.Equals(CurrentUser.UserName)).First();
                if (currentUserDto != null)
                {
                    currentUserId = currentUserDto.UserId;
                }
            }

            var listQueryable = _db.Queryable<EngineeringBatchCancelOrdersHeader, EngineeringBatchCancelOrdersDetail, BusinessProcessesNew>(
                    (x, m, b) => new JoinQueryInfos(JoinType.Left, x.InstanceNumber == m.InstanceNumber, JoinType.Left, x.InstanceNumber == b.InstanceId)
                ).WhereIF(!input.IsQueryAll, x => x.AddUserId.Equals(currentUserId))
                .WhereIF(!string.IsNullOrWhiteSpace(input.InstanceNumber),
                    x => x.InstanceNumber == input.InstanceNumber)
                .WhereIF(!input.OrderStatus.IsNullOrEmpty(),
                    (x, m, b) => SqlFunc.ContainsArray(input.OrderStatus.ToArray(), b.ProcessStatusCode))
                .WhereIF(!string.IsNullOrWhiteSpace(input.AddUserName),
                    (x, m, b) => x.AddUserName.Contains(input.AddUserName))
                .WhereIF(input.StartCreationTime != null && input.EndCreationTime != null,
                    (x, m, b) => b.StartTime >= input.StartCreationTime &&
                              b.StartTime <= input.EndCreationTime)
                .WhereIF(!string.IsNullOrWhiteSpace(input.OrderCenter), (x, m, b) =>
                    x.OrderCenter == input.OrderCenter)
                .WhereIF(!string.IsNullOrWhiteSpace(input.CancelReason), (x, m, b) =>
                    x.CancelReason == input.CancelReason)
                .WhereIF(!string.IsNullOrWhiteSpace(input.SellUserName), (x, m, b) =>
                    x.SellUserName == input.SellUserName)
                .WhereIF(!string.IsNullOrWhiteSpace(input.ReasonClassification), (x, m, b) =>
                    x.ReasonClassification == input.ReasonClassification)
                .WhereIF(!string.IsNullOrWhiteSpace(input.IsProductionFees), (x, m, b) =>
                    x.IsProductionFees == input.IsProductionFees)
                .WhereIF(!string.IsNullOrWhiteSpace(input.SalesOrganization), (x, m, b) =>
                    x.SalesOrganization == input.SalesOrganization)
                .WhereIF(!string.IsNullOrWhiteSpace(input.CostCenterCredit), (x, m, b) =>
                    x.CostCenterCredit == input.CostCenterCredit)
                .WhereIF(!string.IsNullOrWhiteSpace(input.IsNeedInvoice), (x, m, b) =>
                    x.IsNeedInvoice == input.IsNeedInvoice)
                .WhereIF(!string.IsNullOrWhiteSpace(input.InvoiceTitle), (x, m, b) =>
                    x.InvoiceTitle == input.InvoiceTitle)
                .WhereIF(!string.IsNullOrWhiteSpace(input.Division), (x, m, b) =>
                    x.Division == input.Division)
                .Select((x, m, b) => new GetEngineeringBatchCancelOrdersOutput()
                {
                    UserName = x.AddUserName,
                    AddUserId = x.AddUserId,
                    InstanceNumber = x.InstanceNumber,
                    OrderStatus = b.ProcessStatusName,
                    CreateTime = b.StartTime.ToString(),
                    CancelReason = x.CancelReason,
                    CostCenterCredit = x.CostCenterCredit,
                    InvoiceTitle = x.InvoiceTitle,
                    IsNeedInvoice = x.IsNeedInvoice,
                    IsProductionFees = x.IsProductionFees,
                    OrderCenter = x.OrderCenter,
                    ReasonClassification = x.ReasonClassification,
                    Remark = x.Remark,
                    SalesOrganization = x.SalesOrganization,
                    SellUserName = x.SellUserName,
                    Division = x.Division,
                    SalesVoucher = m.SalesVoucher,
                    CustomerName = m.CustomerName,
                    ProjectName = m.ProjectName,
                    OpportunityNumber = m.OpportunityNumber,
                    MaterialName = m.MaterialName,
                    MaterialCode = m.MaterialCode,
                    CancelQuantity = m.CancelQuantity,
                    CancelOrderInvoiceAmount = m.CancelOrderInvoiceAmount,
                    OrderDate = m.OrderDate,
                    SluggishCompletionDate = m.SluggishCompletionDate,
                    SluggishProductSolution = m.SluggishProductSolution,
                    SluggishGoodsPrice = m.SluggishGoodsPrice,
                    SluggishProductBatchNumber = m.SluggishProductBatchNumber,
                    IsEnd = b.IsEnd
                }).MergeTable().Distinct().OrderBy(ins => ins.InstanceNumber, OrderByType.Desc);
            return listQueryable;
        }
        #endregion

        #region 一体板加急生产申请流程

        public async Task<PagedResultDto<GetYTBUrgentApplicationOutput>> GetAllAsync(GetYTBUrgentApplicationInput input)
        {
            RefAsync<int> totalCount = 0;

            var listQueryable = GetQueryable(input);
            var listViewDto = await listQueryable.ToPageListAsync(input.PageIndex, input.PageSize, totalCount);

            var userId = await _iBPMPlatformApp.GetUserAsync(CurrentUser.UserName);

            listViewDto.ForEach(x => x.Url = _bPMUtilsApp.GetProcessUrl(x.InstanceNumber, userId));

            //返回结果
            return new PagedResultDto<GetYTBUrgentApplicationOutput>()
            {
                TotalCount = totalCount,
                Items = listViewDto
            };
        }

        public async Task<List<GetYTBUrgentApplicationOutput>> ExportAsync(GetYTBUrgentApplicationInput input)
        {
            var listQueryable = GetQueryable(input);
            var listViewDto = await listQueryable.ToListAsync();
            return listViewDto;
        }


        private ISugarQueryable<GetYTBUrgentApplicationOutput> GetQueryable(GetYTBUrgentApplicationInput input)
        {
            var currentUserId = Guid.Empty;
            if (!input.IsQueryAll)
            {
                var currentUserDto = _dbPlatform.Queryable<Users>()
                    .Where(x => x.WorkNumber.Equals(CurrentUser.UserName)).First();
                if (currentUserDto != null)
                {
                    currentUserId = currentUserDto.UserId;
                }
            }

            var listQueryable = _db.Queryable<YTBUrgentApplicationHeader, BusinessProcessesNew>(
                    (x, b) => new JoinQueryInfos(JoinType.Left, x.InstanceNumber == b.InstanceId)
                ).WhereIF(!input.IsQueryAll, (x, b) => b.StartUserId.Equals(currentUserId))
                .WhereIF(!string.IsNullOrWhiteSpace(input.InstanceNumber),
                    x => x.InstanceNumber == input.InstanceNumber)
                .WhereIF(!input.OrderStatus.IsNullOrEmpty(),
                    (x, b) => SqlFunc.ContainsArray(input.OrderStatus.ToArray(), b.ProcessStatusCode))
                .WhereIF(!string.IsNullOrWhiteSpace(input.AddUserName),
                    (x, b) => b.StartUserName.Contains(input.AddUserName))
                .WhereIF(input.StartCreationTime != null && input.EndCreationTime != null,
                    (x, b) => b.StartTime >= input.StartCreationTime &&
                              b.StartTime <= input.EndCreationTime)
                .WhereIF(!string.IsNullOrWhiteSpace(input.ApplicationUserNames), (x, b) =>
                    x.ApplicationUserNames == input.ApplicationUserNames)
                .WhereIF(!string.IsNullOrWhiteSpace(input.SellUserNames), (x, b) =>
                    x.SellUserNames == input.SellUserNames)
                .WhereIF(!string.IsNullOrWhiteSpace(input.OpportunityNumber), (x, b) =>
                    x.OpportunityNumber == input.OpportunityNumber)
                .WhereIF(!string.IsNullOrWhiteSpace(input.ProjectName), (x, b) =>
                    x.ProjectName == input.ProjectName)
                .WhereIF(!string.IsNullOrWhiteSpace(input.OrderNumber), (x, b) =>
                    x.OrderNumber == input.OrderNumber)
                .WhereIF(!string.IsNullOrWhiteSpace(input.ProductionPlant), (x, b) =>
                    x.ProductionPlant == input.ProductionPlant)
                .WhereIF(!string.IsNullOrWhiteSpace(input.ApplicationReason), (x, b) =>
                    x.ApplicationReason == input.ApplicationReason)
                .Select((x, b) => new GetYTBUrgentApplicationOutput()
                {
                    UserName = b.StartUserName,
                    InstanceNumber = x.InstanceNumber,
                    OrderStatus = b.ProcessStatusName,
                    CreateTime = b.StartTime.ToString(),
                    ProjectName = x.ProjectName,
                    ApplicationReason = x.ApplicationReason,
                    ApplicationUserNames = x.ApplicationUserNames,
                    CcUserNames = x.CcUserNames,
                    Url = "",
                    CreateOrderDate = x.CreateOrderDate,
                    ExpeditedStorageDate = x.ExpeditedStorageDate,
                    OpportunityNumber = x.OpportunityNumber,
                    OrderNumber = x.OrderNumber,
                    ProductionPlant = x.ProductionPlant,
                    SellUserNames = x.SellUserNames
                });
            return listQueryable;
        }

        #endregion

        #region 一体板产品色号维护申请表

        public async Task<PagedResultDto<GetYTBCPSHWHSQBOutput>> GetAllAsync(GetYTBCPSHWHSQBInput input)
        {
            RefAsync<int> totalCount = 0;

            var listQueryable = GetQueryable(input);
            var listViewDto = await listQueryable.ToPageListAsync(input.PageIndex, input.PageSize, totalCount);

            var userId = await _iBPMPlatformApp.GetUserAsync(CurrentUser.UserName);

            listViewDto.ForEach(x => x.Url = _bPMUtilsApp.GetProcessUrl(x.InstanceNumber, userId));

            //返回结果
            return new PagedResultDto<GetYTBCPSHWHSQBOutput>()
            {
                TotalCount = totalCount,
                Items = listViewDto
            };
        }

        public async Task<List<GetYTBCPSHWHSQBOutput>> ExportAsync(GetYTBCPSHWHSQBInput input)
        {
            var listQueryable = GetQueryable(input);
            var listViewDto = await listQueryable.ToListAsync();
            return listViewDto;
        }

        private ISugarQueryable<GetYTBCPSHWHSQBOutput> GetQueryable(GetYTBCPSHWHSQBInput input)
        {
            var currentUserId = Guid.Empty;
            if (!input.IsQueryAll)
            {
                var currentUserDto = _dbPlatform.Queryable<Users>()
                    .Where(x => x.WorkNumber.Equals(CurrentUser.UserName)).First();
                if (currentUserDto != null)
                {
                    currentUserId = currentUserDto.UserId;
                }
            }

            var listQueryable = _db.Queryable<YTBCPSHWHSQBHeader, BusinessProcessesNew>(
                    (x, b) => new JoinQueryInfos(JoinType.Left, x.InstanceNumber == b.InstanceId)
                ).WhereIF(!input.IsQueryAll, (x, b) => b.StartUserId.Equals(currentUserId))
                .WhereIF(!string.IsNullOrWhiteSpace(input.InstanceNumber),
                    x => x.InstanceNumber == input.InstanceNumber)
                .WhereIF(!input.OrderStatus.IsNullOrEmpty(),
                    (x, b) => SqlFunc.ContainsArray(input.OrderStatus.ToArray(), b.ProcessStatusCode))
                .WhereIF(!string.IsNullOrWhiteSpace(input.AddUserName),
                    (x, b) => b.StartUserName.Contains(input.AddUserName))
                .WhereIF(input.StartCreationTime != null && input.EndCreationTime != null,
                    (x, b) => b.StartTime >= input.StartCreationTime &&
                              b.StartTime <= input.EndCreationTime)
                .WhereIF(!string.IsNullOrWhiteSpace(input.OpportunityNumber), (x, b) =>
                    x.OpportunityNumber == input.OpportunityNumber)
                .WhereIF(!string.IsNullOrWhiteSpace(input.ProductionPlant), (x, b) =>
                    x.ProductionPlant == input.ProductionPlant)
                .WhereIF(!string.IsNullOrWhiteSpace(input.ProjectStatus), (x, b) =>
                    x.ProjectStatus == input.ProjectStatus)
                .WhereIF(!string.IsNullOrWhiteSpace(input.ProjectArea), (x, b) =>
                    x.ProjectArea == input.ProjectArea)
                .WhereIF(!string.IsNullOrWhiteSpace(input.OpportunityName), (x, b) =>
                    x.OpportunityName == input.OpportunityName)
                .WhereIF(!string.IsNullOrWhiteSpace(input.QAUsersName), (x, b) =>
                    x.QAUsersName == input.QAUsersName)
                .WhereIF(!string.IsNullOrWhiteSpace(input.SellUserPhoneNumber), (x, b) =>
                    x.SellUserPhoneNumber == input.SellUserPhoneNumber)
                .WhereIF(!string.IsNullOrWhiteSpace(input.IsFirstBomEdition), (x, b) =>
                    x.IsFirstBomEdition == input.IsFirstBomEdition)
                .Select((x, b) => new GetYTBCPSHWHSQBOutput()
                {
                    UserName = b.StartUserName,
                    InstanceNumber = x.InstanceNumber,
                    OrderStatus = b.ProcessStatusName,
                    CreateTime = b.StartTime.ToString(),
                    Url = "",
                    OpportunityNumber = x.OpportunityNumber,
                    ProductionPlant = x.ProductionPlant,
                    ProjectArea = x.ProjectArea,
                    IsFirstBomEdition = x.IsFirstBomEdition,
                    OpportunityName = x.OpportunityName,
                    ProjectStatus = x.ProjectStatus,
                    QAUsersName = x.QAUsersName,
                    SellUserPhoneNumber = x.SellUserPhoneNumber
                });
            return listQueryable;
        }

        #endregion

        #region 账期调整申请流程

        public async Task<PagedResultDto<GetAccountPeriodAdjustmentApplicationOutput>> GetAllAsync(
            GetAccountPeriodAdjustmentApplicationInput input)
        {
            RefAsync<int> totalCount = 0;

            var listQueryable = await GetQueryable(input);
            var listViewDto = await listQueryable.ToPageListAsync(input.PageIndex, input.PageSize, totalCount);

            var userId = await _iBPMPlatformApp.GetUserAsync(CurrentUser.UserName);
            listViewDto.ForEach(x => { x.Url = _bPMUtilsApp.GetProcessUrl(x.InstanceNumber, userId); });

            //返回结果
            return new PagedResultDto<GetAccountPeriodAdjustmentApplicationOutput>()
            {
                TotalCount = totalCount,
                Items = listViewDto
            };
        }

        public async Task<List<GetAccountPeriodAdjustmentApplicationOutput>> ExportAsync(
            GetAccountPeriodAdjustmentApplicationInput input)
        {
            var listQueryable = await GetQueryable(input);
            var listViewDto = await listQueryable.ToListAsync();
            return listViewDto;
        }


        private async Task<ISugarQueryable<GetAccountPeriodAdjustmentApplicationOutput>> GetQueryable(
            GetAccountPeriodAdjustmentApplicationInput input)
        {
            var currentUserId = Guid.Empty;
            if (!input.IsQueryAll)
            {
                var currentUserDto = _dbPlatform.Queryable<Users>()
                    .Where(x => x.WorkNumber.Equals(CurrentUser.UserName)).First();
                if (currentUserDto != null)
                {
                    currentUserId = currentUserDto.UserId;
                }
            }

            var authDto = new AccountPeriodAdjustmentApplicationAuthDto();
            var authUser = await _db.Queryable<AccountPeriodAdjustmentApplicationAuth>().FirstAsync(x => x.Status == 1
                    && x.WorkNumber.Equals(CurrentUser.UserName));
            var authAreas = new List<string>();
            var authCompanys = new List<string>();
            if (authUser != null)
            {
                authDto = JsonConvert.DeserializeObject<AccountPeriodAdjustmentApplicationAuthDto>(authUser.AuthOption);
                authCompanys = authDto.CompanyCode.Split(',').ToList();
                authAreas = authDto.AreaCode.Split(',').ToList();
            }

            var isAuthUser = authUser != null;

            var listQueryable =
                _db.Queryable<AccountPeriodAdjustmentApplicationHeader, AccountPeriodAdjustmentApplicationDetail,
                        BusinessProcessesNew>
                    ((a, b, c) => new JoinQueryInfos(JoinType.Inner, a.InstanceNumber == b.InstanceNumber,
                        JoinType.Left,
                        b.InstanceNumber == c.InstanceId))
                    .WhereIF(!string.IsNullOrWhiteSpace(input.InstanceNumber),
                        (a, b, c) => a.InstanceNumber == input.InstanceNumber)
                    .WhereIF(!input.OrderStatus.IsNullOrEmpty(),
                        (a, b, c) => SqlFunc.ContainsArray(input.OrderStatus.ToArray(), c.ProcessStatusCode))
                    .WhereIF(!string.IsNullOrWhiteSpace(input.AddUserName),
                        (a, b, c) => c.StartUserName.Contains(input.AddUserName))
                    .WhereIF(input.StartCreationTime != null && input.EndCreationTime != null,
                        (a, b, c) => c.StartTime >= input.StartCreationTime &&
                                     c.StartTime <= input.EndCreationTime)
                    .WhereIF(!input.IsQueryAll && input.IsAuthAll ||
                        (!input.IsQueryAll && !input.IsAuthAll && !isAuthUser), 
                        (a, b, c) => c.StartUserId == currentUserId)
                    .WhereIF(!input.IsQueryAll && !input.IsAuthAll && isAuthUser && !authDto.IsAreaAll,
                        (a, b, c) => SqlFunc.ContainsArray(authAreas, a.Area))
                    .WhereIF(!input.IsQueryAll && !input.IsAuthAll && isAuthUser && !authDto.IsCompanyAll,
                        (a, b, c) => SqlFunc.ContainsArray(authCompanys, a.CompanyCode))
                    .WhereIF(!input.CompanyCode.IsNullOrEmpty(),
                        (a, b, c) => SqlFunc.Contains(a.CompanyCode, input.CompanyCode))
                    .WhereIF(!input.Area.IsNullOrEmpty(),
                        (a, b, c) => SqlFunc.Contains(a.Area, input.Area))
                    .WhereIF(!input.SignalControlRange.IsNullOrEmpty(),
                        (a, b, c) => SqlFunc.Contains(a.SignalControlRange, input.SignalControlRange))
                    .WhereIF(!input.AdjustContent.IsNullOrEmpty(),
                        (a, b, c) => SqlFunc.Contains(a.AdjustContent, input.AdjustContent))
                    .WhereIF(!input.CustomerCode.IsNullOrEmpty(),
                        (a, b, c) => b.CustomerCode.Contains(input.CustomerCode))
                    .WhereIF(!input.CustomerName.IsNullOrEmpty(),
                        (a, b, c) => b.CustomerName.Contains(input.CustomerName))
                    .Select((a, b, c) => new GetAccountPeriodAdjustmentApplicationOutput
                    {
                        CompanyCode = a.CompanyCode,
                        AdjustContent = a.AdjustContent,
                        Area = a.Area,
                        CCUsersName = a.CCUsersName,
                        Content = a.Content,
                        InstanceNumber = a.InstanceNumber,
                        Remark = a.Remark,
                        SignalControlRange = a.SignalControlRange,
                        CreateTime = c.StartTime != null
                            ? c.StartTime.ToString()
                            : DateTime.MinValue.ToString(CultureInfo.InvariantCulture),
                        OrderStatus = c.ProcessStatusName,
                        UserName = c.StartUserName,
                        CustomerCode = b.CustomerCode,
                        CustomerName = b.CustomerName,
                    });

            return listQueryable.MergeTable().OrderBy(x => x.InstanceNumber, OrderByType.Desc);
        }

        public async Task<List<GetAccountPeriodAdjustmentApplicationApproverOutput>> ExportApproverAsync(
            GetAccountPeriodAdjustmentApplicationApproverInput input)
        {
            var userIds = _dbPlatform.Queryable<Users>()
                .Where(x => input.UserCodes.Contains(x.UserLoginId) || input.UserCodes.Contains(x.WorkNumber))
                .Select(x => SqlFunc.ToString(x.UserId)).ToList();

            var query = _dbEngine.Queryable<Instances, InstanceStates, Tasks>(
                (i, s, r) => i.InstanceId == s.InstanceId && i.InstanceId == r.InstanceId)
                .Where((i, s, r) => i.BTID == "AccountPeriodAdjustmentApplication")
                .WhereIF(input.UserCodes.Any(), (i, s, r) => userIds.Contains(r.ResolveUserId))
                .WhereIF(input.StartTime != null && input.EndTime != null && input.SearchTimeType == "1",
                    (i, s, r) => s.StartTime <= input.EndTime && s.StartTime >= input.StartTime)
                .WhereIF(input.StartTime != null && input.EndTime != null && input.SearchTimeType == "2",
                    (i, s, r) => r.FinishTime <= input.EndTime && r.FinishTime >= input.StartTime)
                .WhereIF(input.StartTime != null && input.EndTime != null && input.SearchTimeType == "3",
                    (i, s, r) => s.StartTime <= input.EndTime && s.StartTime >= input.StartTime ||
                    r.FinishTime <= input.EndTime && r.FinishTime >= input.StartTime)
                .WhereIF(input.OrderStatus.Any(), (i, s, r) => input.OrderStatus.Contains(s.Status))
                .WhereIF(input.OpearteType.Any(), (i, s, r) => input.OpearteType.Contains(SqlFunc.ToInt32(r.Status)))
                .Select((i, s, r) => new GetAccountPeriodAdjustmentApplicationApproverOutput
                {
                    AddTime = s.StartTime.ToString(DateFormatHelper.DateTimeFormat),
                    AddUser = i.StartUserName,
                    OperateTime = r.FinishTime != null ? r.FinishTime.Value.ToString(DateFormatHelper.DateTimeFormat) : "",
                    OperateUser = r.ResolveUserName,
                    InstanceNumber = r.InstanceNumber,
                    InstanceTopic = i.Topic,
                    Status = s.StatusName,
                    ResolveStatus = r.Status
                }).MergeTable().OrderBy(x => x.AddTime, OrderByType.Desc);
            var listQueryable = query.InnerJoin<AccountPeriodAdjustmentApplicationHeader>(
                (i, a) => i.InstanceNumber == a.InstanceNumber)
                .AS<AccountPeriodAdjustmentApplicationHeader>("BPM_Business.AccountPeriodAdjustmentApplicationHeader")
                .Select((i, a) => new GetAccountPeriodAdjustmentApplicationApproverOutput
                {
                    AddTime = i.AddTime,
                    AddUser = i.AddUser,
                    OperateTime = i.OperateTime,
                    OperateUser = i.OperateUser,
                    InstanceNumber = i.InstanceNumber,
                    InstanceTopic = i.InstanceTopic,
                    InstanceType = "账期调整申请",
                    Status = i.Status,
                    ResolveStatus = i.ResolveStatus,
                    Area = a.Area,
                    CompanyCode = a.CompanyCode,
                    AdjustContent = a.AdjustContent,
                    SignalControlRange = a.SignalControlRange,
                    Content = a.Content,
                    CCUsersName = a.CCUsersName,
                    Remark = a.Remark,
                });
            var listViewDto = await listQueryable.ToListAsync();
            listViewDto.ForEach(x =>
            {
                if (x.ResolveStatus.HasValue)
                {
                    x.Summary = EnumHelper.GetEnumDesc<TaskCommonStatus>(x.ResolveStatus.Value);
                }
            });
            return listViewDto;
        }

        #endregion


        #region 设计依赖书
        /// <summary>
        /// 查询数据 设计依赖书
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<PagedResultDto<DesignDependencyBookOutput>> GetAllAsync(
            DesignDependencyBookInput input)
        {
            RefAsync<int> totalCount = 0;
            var listQueryable = GetQueryable(input);
            var listViewDto = await listQueryable.ToPageListAsync(input.PageIndex, input.PageSize, totalCount);

            var userId = await _iBPMPlatformApp.GetUserAsync(CurrentUser.UserName);
            listViewDto.ForEach(x => { x.Url = _bPMUtilsApp.GetProcessUrl(x.InstanceNumber, userId); });

            //返回结果
            return new PagedResultDto<DesignDependencyBookOutput>()
            {
                TotalCount = totalCount,
                Items = listViewDto
            };
        }

        /// <summary>
        /// 导出数据 设计依赖书
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<List<DesignDependencyBookOutput>> ExportAsync(DesignDependencyBookInput input)
        {
            var listQueryable = GetQueryable(input);
            var listViewDto = await listQueryable.ToListAsync();
            return listViewDto;
        }

        private ISugarQueryable<DesignDependencyBookOutput> GetQueryable(DesignDependencyBookInput input)
        {
            var listQueryable = _db.Queryable<TUDesignDependencyBookHeader, TUDesignDependencyBookQuotedDetails>(
                    (x, d) => new JoinQueryInfos(JoinType.Left, x.InstanceNumber == d.InstanceNumber))
                .WhereIF(!string.IsNullOrWhiteSpace(input.InstanceNumber), x => x.InstanceNumber == input.InstanceNumber)
                .WhereIF(!string.IsNullOrWhiteSpace(input.AddUserName), x => x.AddUserName.Contains(input.AddUserName))
                .Select((x, d) =>
                    new DesignDependencyBookOutput()
                    {
                        InstanceNumber = x.InstanceNumber,
                        AddTime = x.AddTime,
                        AddUserName = x.AddUserName,
                        StateText = x.StateText,
                        AddUserOrg = x.AddUserOrg,
                        DesignCase = x.DesignCase,
                        BusinessNum = x.BusinessNum,
                        ProjectName = x.ProjectName,
                        ProjectType = x.ProjectType,
                        ProjectAttr = x.ProjectAttr,
                        ProjectLocation = x.ProjectLocation,
                        Factory = x.Factory,
                        CustomerName = x.CustomerName,
                        CustomerLinkName = x.CustomerLinkName,
                        CustomerTel = x.CustomerTel,
                        DesignAim = x.DesignAim,
                        PlanProductSystem = x.PlanProductSystem,
                        DesignContent = x.DesignContent,
                        ExpectPlotDate = x.ExpectPlotDate,
                        ProgrammeCount = x.ProgrammeCount,
                        SceneProposalSupport = x.SceneProposalSupport,
                        DrawingCount = x.DrawingCount,
                        AreaCost = x.AreaCost,
                        Designer = x.Designer,
                        AdditionalCost = x.AdditionalCost,
                        Adopt = x.Adopt,
                        QuotedPrice = d.QuotedPrice,
                        Note=d.Note
                    }).MergeTable().Distinct().OrderBy(ins => ins.AddTime, OrderByType.Desc);

            return listQueryable;
        }


        #endregion
    }
}